package com.woniu.woniuticket.controller;


import com.woniu.woniuticket.common.Result;
import com.woniu.woniuticket.entity.School;
import com.woniu.woniuticket.service.ISchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author spirit
 * @since 2020-01-02
 */
@RestController
@RequestMapping("/woniuticket/school")
@CrossOrigin("*")
public class SchoolController {

    @Autowired
    private ISchoolService iss;

    //登陆之后获取资质状态和资质文件
    @RequestMapping("/firstqualification")
    public Result firstQualification(String schoolName) {
        System.out.println(schoolName);
        School result = iss.firstqualification(schoolName);
        System.out.println("first"+result);
        return Result.success(result);
    }

    //上传资质表单
    @Transactional
    @RequestMapping("/upload")
    public Result upload(@RequestParam(value = "schoolname", required = false) String schoolname,
                         @RequestParam(value = "address", required = false) String address,
                         @RequestParam(value = "accountpayee", required = false) String accountpayee,
                         @RequestParam(value = "file", required = false) MultipartFile file
    ) {
        //获取上传文件名，包含后缀的
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        //获取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String saveName = UUID.randomUUID()+suffix;
        //保存路径
        String path = Objects.requireNonNull(Objects.requireNonNull(ClassUtils.getDefaultClassLoader())
                .getResource("")).getPath();
        //创建文件
        File localFile = new File(path+"static/"+saveName);
        //保存到本地
        try {
            file.transferTo(localFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        School school = new School();
        System.out.println("sn:"+schoolname+"add"+address+"status"+accountpayee);
        school.setSchoolName(schoolname).setSchoolAddress(address).setSchoolStatus("未通过").
                setSchoolAccountPayee(accountpayee).setSchoolQualification(saveName);
        System.out.println("sn:"+schoolname+"add"+address+"status"+accountpayee+"~~~"+school.getSchoolStatus());
        boolean result = iss.save(school);
        System.out.println(school.toString());
        return Result.success(result);
    }


    @RequestMapping("/getmoney")
    public Result getMoney(){
        Map result = iss.getMoney();
        return Result.success(result);
    }
}

